package com.wistech.search.solr.extend;

import java.io.IOException;
import java.util.List;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

import com.google.common.collect.Lists;

/**
 * 过滤器集合
 * 
 * @author Liuye
 * 
 */
@SuppressWarnings("serial")
public class FilterSet extends Filter {
	private List<Filter> filters = Lists.newArrayList();

	public void addFilter(Filter filter) {
		filters.add(filter);
	}

	@Override
	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
		if (filters.isEmpty()) {
			return new OpenBitSet();
		}
		if (filters.size() == 1) {
			return filters.get(0).getDocIdSet(reader);
		}
		int i = 0;
		OpenBitSet obs = convert2BitSet(filters.get(i).getDocIdSet(reader));
		while (obs.cardinality() > 0 && i < filters.size() - 1) {
			i++;
			obs.and(convert2BitSet(filters.get(i).getDocIdSet(reader)));
		}
		return obs;
	}

	private OpenBitSet convert2BitSet(DocIdSet docSet) throws IOException {
		OpenBitSet obs = new OpenBitSet();
		DocIdSetIterator it = docSet.iterator();
		int doc;
		while ((doc = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
			obs.set(doc);
		}
		return obs;
	}
}
